﻿using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug.VDDIC_Gamma
{
    public partial class NT38360_Gamma : Form
    {

        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke 
        ListBox[] listbox = new ListBox[12];

        NumericUpDown[] Rvalue = new NumericUpDown[32];
        NumericUpDown[] Gvalue = new NumericUpDown[32];
        NumericUpDown[] Bvalue = new NumericUpDown[32];
        List<NumericUpDown> my = new List<NumericUpDown>();
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过

        private byte[] Rec_tmp = new byte[1];

        private static bool Gamma_adjust_timeout_flag = false;
        Color[] listBoxBackColor = new Color[3] { Color.Red, Color.Green, Color.Blue };
        string[] strRGB = new string[3] { "R", "G", "B" };

        int Total_points = 0;

        int error_flag = 0;   //0:ok,否则格式错误
        private int index = 0;
        private int flag1 = 1; //lum
        private int flag2 = 1; //x
        private int flag3 = 1; //y
        frmMain frmHelp = null;

        #region //多绑点需要更改的地方  regType=0
        #region //regType=0

        //string[] gammaPointSelect = { "fe,70", "28,00", "fe,40", "da,e0", "fe,78", "f4,c0" };   // 15piont
        string[] dbv = new string[17] { "51,00,0a", "51,00,18", "51,00,2e", "51,00,58", "51,00,e4", "51,02,22", "51,05,55", "51,07,ff", "51,0f,ff", "51,00,0a", "51,00,18", "51,00,2e", "51,00,58", "51,00,e4", "51,02,22", "51,05,55", "51,07,ff" };
        string[] enter = { "fe,70", "28,00", "fe,40", "da,ca", "d7,xx", "fe,78", "f4,c0", "f5,xx" };  //xx是需要替换的值
        string[] outer = { "fe,40", "da,88", "fe,78", "f4,80", "fe,70", "28,01" };
        string[] setGamma = new string[17] { "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0c", "0d", "0e", "0f", "10", "11", "12", "13" };


        #endregion
        #region //regType=1
        string[] gammaPage_1 = { "ff,21" };
        string[] gammaPoint_1 = { "" };
        ushort[] gamma_Type1_gamma1_25 = new ushort[] { 0xB2, 0x10, 0xB3, 0x10, 0xB4, 0x10, 0xB5, 0x02, 0xB6, 0x10, 0xB7, 0x10, 0xB8, 0x10, 0xB9, 0x02, 0xBA, 0x10, 0xBB, 0x10, 0xBC, 0x10, 0xBD, 0x02 };//寄存器+回读个数
        int[] regRmapping25 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 };//读到的寄存器值高位在前，结合寄存器，低灰阶在前
        int[] regGmapping25 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 };//读到的寄存器值高位在前，结合寄存器，低灰阶在前
        int[] regBmapping25 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 };//读到的寄存器值高位在前，结合寄存器，低灰阶在前
        private void get_reg_address()
        {
            if (regType == 0)
            {

            }
            else if (regType == 1)
            {

                List<ushort[]> tmpGammaSet25 = new List<ushort[]> { gamma_Type1_gamma1_25 };
                //  List<ushort[]> tmpGammaSet15 = new List<ushort[]> { gamma_Type1_gamma1_15, gamma_Type1_gamma2_15, gamma_Type1_gamma3_15, gamma_Type1_gamma4_15, gamma_Type1_gamma5_15 };
                if (rb_27_point.Checked == true)
                {

                }
                else if (rb_other_point.Checked == true)
                {
                    gamma_r = gamma_Type1_gamma1_25;
                    currentRmapping = regRmapping25;
                    currentGmapping = regGmapping25;
                    currentBmapping = regBmapping25;
                }
                else   //非实际绑点default如下 防止越界
                {
                    gamma_r = new ushort[32];
                    gamma_g = new ushort[32];
                    gamma_b = new ushort[32];
                }
            }
        }
        private void gammaSetSelect(int a)
        {

            DDIC_Reg_write("B1," + a.ToString());   //切dbv
        }
        private void gammaPiontSet()
        {
            //for (int i = 0; i < gammaPointSelect.Length; i++)
            //{
            //    DDIC_Reg_write(gammaPointSelect[i]);
            //}

        }
        private void existGamma()
        {
            for (int i = 0; i < outer.Length; i++)
            {
                DDIC_Reg_write(outer[i]);
            }
        }

        #region// 全局变量
        int regType = 1;       //0:寄存器一对一方式  1：寄存器一对多方式   zhongyao 
        ushort[] gamma_r = new ushort[] { };   //reg address
        ushort[] gamma_g = new ushort[] { };
        ushort[] gamma_b = new ushort[] { };
        ushort[] gamma_r_1 = new ushort[] { };
        ushort[] gamma_g_1 = new ushort[] { };
        ushort[] gamma_b_1 = new ushort[] { };
        int[] currentBmapping = new int[] { };
        int[] currentGmapping = new int[] { };
        int[] currentRmapping = new int[] { };
        int currentGammaSet = 0;
        #endregion
        Regex reg;
        #endregion //多绑点需要更改的地方
        //Gamma保存
        private void delay_ms(int time)
        {
            byte[] Send_buf = new byte[2 + 5];
            Send_buf[0] = 0x80;//NT38360
            Send_buf[1] = 0x03;//NT38360
            Send_buf[2] = 0x02;

            Send_buf[3] = (byte)(time >> 8 & 0xff);
            Send_buf[4] = (byte)(time & 0xff);
            CRCData.CalculateCrc16(Send_buf, out Send_buf[2 + 5 - 2], out Send_buf[2 + 5 - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 2 + 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        private void DDIC_Reg_write(string str)
        {
            string[] strt = str.Split(',');
            byte[] Send_buf = new byte[strt.Length + 5];
            Send_buf[0] = 0x80;//NT38360
            Send_buf[1] = 0x01;//NT38360
            Send_buf[2] = (byte)strt.Length;
            Setting.TempRecord.cmdLen = Send_buf[2] + 5;

            if (str == "")
                return;
            else
            {
                try
                {
                    for (int i = 0; i < strt.Length; i++)
                    {
                        Send_buf[3 + i] = byte.Parse((Convert.ToInt32(strt[i], 16)).ToString());
                    }

                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
                CRCData.CalculateCrc16(Send_buf, out Send_buf[strt.Length + 5 - 2], out Send_buf[strt.Length + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, strt.Length + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
        }
        private void DDIC_Reg_read(string str)
        {
            string[] strt = str.Split(',');
            byte[] Send_buf = new byte[Convert.ToInt16(strt.Length) + 5];
            Send_buf[0] = 0x80;//NT38360
            Send_buf[1] = 0x02;//NT38360

            Send_buf[2] = (byte)strt.Length;
            if (str == "")
                return;
            Setting.TempRecord.cmdLen = Convert.ToInt32(strt[1], 16) + 1 + 5;


            try
            {
                for (int i = 0; i < strt.Length; i++)
                {
                    Send_buf[3 + i] = byte.Parse((Convert.ToInt32(strt[i], 16)).ToString());
                }
                Setting.TempRecord.cmdLen = Send_buf[4] + 6;
            }
            catch
            {
                MessageBox.Show("格式输入有误");
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[strt.Length + 5 - 2], out Send_buf[strt.Length + 5 - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, strt.Length + 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }


        }
        private void Gamma_read_all(int type)
        {
            if (type == 0)
            {
                byte[] Send_buf = new byte[Total_points * 6 + 5];
                // System.Diagnostics.Debug.Print("sendbuf length =" + Send_buf.Length.ToString());
                Setting.TempRecord.cmdLen = Total_points * 6 + 5;

                Send_buf[0] = 0x80;//NT38360
                Send_buf[1] = 0x06; //register normal gamma

                Send_buf[2] = Convert.ToByte(Total_points * 6); //length
                for (int i = 0; i < Total_points; i++)

                {
                    Send_buf[2 * i + 3] = Convert.ToByte(gamma_r[i] >> 8);   //高位
                    Send_buf[2 * i + 4] = Convert.ToByte(gamma_r[i] & 0xff);    //低位

                    Send_buf[Total_points * 2 + 2 * i + 3] = Convert.ToByte(gamma_g[i] >> 8);   //高位
                    Send_buf[Total_points * 2 + 2 * i + 4] = Convert.ToByte(gamma_g[i] & 0xff);    //低位

                    Send_buf[Total_points * 4 + 2 * i + 3] = Convert.ToByte(gamma_b[i] >> 8);   //高位
                    Send_buf[Total_points * 4 + 2 * i + 4] = Convert.ToByte(gamma_b[i] & 0xff);    //低位

                }
                string str = "";
                for (int i = 3; i < Total_points * 6 + 5; i++)
                {
                    str = str + String.Format("{0:X4}", Send_buf[i]) + ",";
                    if ((i - 3) % Total_points == 0)
                    {
                        str = str + "\r\n";
                    }
                }
                // System.Diagnostics.Debug.Print(str);
                CRCData.CalculateCrc16(Send_buf, out Send_buf[Total_points * 6 + 5 - 2], out Send_buf[Total_points * 6 + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, Total_points * 6 + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
            else if (type == 1)
            {
                Setting.TempRecord.cmdLen = 0;
                byte[] Send_buf = new byte[gamma_r.Length + 5];
                //     System.Diagnostics.Debug.Print("sendbuf length =" + Send_buf.Length.ToString());
                for (int a = 0; a < gamma_r.Length / 2; a++)
                {
                    Setting.TempRecord.cmdLen = Setting.TempRecord.cmdLen + gamma_r[1 + 2 * a];
                }
                Setting.TempRecord.cmdLen = Setting.TempRecord.cmdLen + 5;
                Send_buf[0] = 0x80;//NT38360
                Send_buf[1] = 0x07; //register normal gamma
                Send_buf[2] = (Byte)gamma_r.Length;
                for (int i = 0; i < gamma_r.Length; i++)
                {
                    Send_buf[3 + i] = (byte)gamma_r[i];
                }
                CRCData.CalculateCrc16(Send_buf, out Send_buf[gamma_r.Length + 5 - 2], out Send_buf[gamma_r.Length + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, gamma_r.Length + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
        }
        int dateLeghth = 0;
        private void Gamma_write_all(int type)
        {
            ushort r = 0, g = 0, b = 0;
            if (type == 0)
            {
                for (int i = 0; i < Total_points; i++)

                {
                    r = (ushort)Rvalue[i].Value;
                    g = (ushort)Gvalue[i].Value;
                    b = (ushort)Bvalue[i].Value;
                    Auto_gamma_write(gamma_r[i], r, gamma_g[i], g, gamma_b[i], b);
                }
            }
            else if (type == 1)
            {

                dateLeghth = 0;
                for (int i = 0; i < gamma_r.Length / 2; i++)
                {
                    dateLeghth = dateLeghth + gamma_r[1 + 2 * i] + 2;
                }
                //  System.Diagnostics.Debug.Print(dateLeghth.ToString());
                byte[] Send_buf = new byte[dateLeghth + 5];

                Send_buf[0] = 0x80;//NT38360
                Send_buf[1] = 0x05; //register normal gamma
                Send_buf[2] = (byte)(dateLeghth);

                byte[] tempR = new byte[currentRmapping.Length];
                byte[] tempG = new byte[currentRmapping.Length];
                byte[] tempB = new byte[currentRmapping.Length];
                byte[] temp_all = new byte[currentRmapping.Length * 3];
                //数据和寄存器值开始拼接+映射

                for (int i = 0; i < Total_points; i++)
                {
                    tempR[currentRmapping[2 * i]] = Convert.ToByte((int)Rvalue[i].Value >> 8);
                    tempR[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Rvalue[i].Value & 0xff);
                    tempG[currentRmapping[2 * i]] = Convert.ToByte((int)Gvalue[i].Value >> 8);
                    tempG[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Gvalue[i].Value & 0xff);
                    tempB[currentRmapping[2 * i]] = Convert.ToByte((int)Bvalue[i].Value >> 8);
                    tempB[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Bvalue[i].Value & 0xff);
                }
                tempR.CopyTo(temp_all, 0);
                tempG.CopyTo(temp_all, currentRmapping.Length);
                tempB.CopyTo(temp_all, currentRmapping.Length * 2);
                List<byte> allList = new List<byte>(temp_all);
                int position1 = 0;
                for (int i = 0; i < gamma_r.Length / 2; i++)
                {
                    allList.Insert(0 + position1, (byte)(gamma_r[2 * i + 1] + 1));
                    allList.Insert(1 + position1, (byte)(gamma_r[2 * i]));
                    position1 = position1 + gamma_r[2 * i + 1] + 2;
                }
                for (int j = 0; j < currentRmapping.Length * 3 + gamma_r.Length; j++)
                {
                    Send_buf[3 + j] = allList[j];
                }
                int a = 5;
                a = Total_points;
                CRCData.CalculateCrc16(Send_buf, out Send_buf[dateLeghth + 5 - 2], out Send_buf[dateLeghth + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, dateLeghth + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }

        }
        public NT38360_Gamma()
        {
            //InitializeComponent();
            //btnCalculate_Click(null,null);
            //AddlistBox();
            //AddValueText();
        }
        public NT38360_Gamma(frmMain myfast)
        {
            frmHelp = myfast;
            InitializeComponent();
            AddlistBox();
            AddValueText();
            frmHelp.Child_window_hide_already = true;
            frmHelp.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体   

        }
        private void NT38360_Gamma_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(RM692E1_DataReceived);
            frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
            frmHelp.Child_window_hide_already = false;
            frmHelp.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormClosed！\r\n";
            frmHelp.IC_comboBox.Enabled = true;
            save_current_cfg(null, null);
        }
        private void NT38360_Gamma_VisibleChanged(object sender, EventArgs e)
        {
            if (frmHelp.Child_window_hide_already == false) //子窗体已开启标识
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(RM692E1_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormHide！\r\n";
                frmHelp.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(RM692E1_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormOpened！\r\n";
                frmHelp.Child_window_hide_already = false; //子窗体已开启标识  
            }
        }
        private void RM692E1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (IClosing)
                return;
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmHelp.comPort.BytesToRead;
                byte[] buf = new byte[n];
                byte data;

                frmHelp.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到   
                buffer.Clear();
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    // 0x7E: NT38350 的Gamma读写、寄存器读写、OTP读写    设置  返回
                    if (buffer[0] == 0x80 && Setting.TempRecord.cmdLen > 0)
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, Setting.TempRecord.cmdLen);//正确分析一条数据，从缓存中移除数据。 
                            }
                        }
                    }
                    else
                    {
                        buffer.RemoveRange(0, buffer.Count);
                    }
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        frmHelp.T1.Enabled = false; //停止超时计数
                        if (Rec_tmp[0] == 0x80) //NT38350
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {

                                        //log_txt.Text += "W:";
                                        //for (int i = 0; i < Rec_tmp.Length - 5; i++)
                                        //    log_txt.Text += string.Format("{0:X2}", Rec_tmp[3 + i]) + ",";
                                        //log_txt.Text += "\r\n";


                                    }
                                    break;
                                case 0x02:
                                    {

                                        log_txt.Text += "======================\r\n";
                                        log_txt.Text += "R:";
                                        for (int i = 0; i < Rec_tmp.Length - 5; i++)
                                            log_txt.Text += string.Format("{0:X2}", Rec_tmp[3 + i]) + ",";
                                        log_txt.Text += "\r\n";
                                        log_txt.Text += "======================\r\n";


                                    }
                                    break;
                                case 0x07:    //regType=0
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA Update\t读 OK！\r\n";
                                        for (int i = 0; i < Total_points; i++)
                                        {
                                            Rvalue[i].Value = (((Rec_tmp[3 + currentRmapping[2 * i]]) & 0x0f) << 8) | (Rec_tmp[3 + currentRmapping[2 * i + 1]]);
                                            //  Rvalue[i].Value = Convert.ToInt16(Rec_tmp[3 + currentRmapping[2*i]] )* 256+Convert.ToInt16(Rec_tmp[3 + currentRmapping[2 * i + 1]]);
                                            Gvalue[i].Value = (((Rec_tmp[3 + Total_points * 2 + currentGmapping[2 * i]]) & 0x0f) << 8) | (Rec_tmp[3 + Total_points * 2 + currentGmapping[2 * i + 1]]);
                                            Bvalue[i].Value = (((Rec_tmp[3 + Total_points * 4 + currentBmapping[2 * i]] & 0x0f) << 8)) | (Rec_tmp[3 + Total_points * 4 + currentBmapping[2 * i + 1]]);
                                        }
                                    }
                                    break;
                                case 0x03:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "delay OK！\r\n";
                                    }
                                    break;
                                case 0x04:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA Update\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x08:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x06:     //regType=0
                                    {
                                        try
                                        {
                                            for (int i = 0; i < Total_points; i++)
                                            {
                                                //  System.Diagnostics.Debug.Print(Convert.ToInt16(Rec_tmp[3 + 2 * i]).ToString());
                                                Rvalue[i].Value = ((Rec_tmp[3 + 2 * i]) & 0x0f) << 8 | (Rec_tmp[4 + 2 * i]);
                                                Gvalue[i].Value = ((Rec_tmp[3 + 2 * i + Total_points * 2]) & 0x0f) << 8 | (Rec_tmp[4 + 2 * i + Total_points * 2]);
                                                Bvalue[i].Value = ((Rec_tmp[3 + 2 * i + Total_points * 4]) & 0x0f) << 8 | (Rec_tmp[4 + 2 * i + Total_points * 4]);
                                            }
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t 读OK！\r\n";
                                        }
                                        catch
                                        {
                                            MessageBox.Show("receive error");
                                        }
                                    }
                                    break;
                                case 0x0D:
                                    {

                                    }
                                    break;
                                default: break;
                            }
                        }
                        // frmHelp.textBox1.SelectionStart = this.frmHelp.textBox1.Text.Length;
                        //  frmHelp.textBox1.ScrollToCaret();//滚动到光标处
                        // if (frmHelp.textBox1.Lines.Length > 250) frmHelp.textBox1.Text = null;
                    }));
                }

            }
            finally
            {
                Listening = false;
            }
        }
        #region  //界面设置
        private void AddlistBox()
        {
            for (int a = 0; a < 3; a++)
            {
                for (int i = 0; i < 4; i++)
                {
                    listbox[i + a * 4] = new System.Windows.Forms.ListBox();
                    listbox[i + a * 4].FormattingEnabled = true;
                    listbox[i + a * 4].ItemHeight = 12;
                    listbox[i + a * 4].Location = new System.Drawing.Point(0 + 95 * i, 15 + a * 170);
                    // listbox[i].Name = listName[i+4*a];
                    listbox[i + a * 4].Size = new System.Drawing.Size(50, 168);
                    listbox[i + a * 4].TabIndex = i;
                    listbox[i + a * 4].Font = new System.Drawing.Font("宋体", 15F); ;
                    listbox[i + a * 4].BackColor = listBoxBackColor[a];
                    listbox[i + a * 4].ForeColor = Color.Black;
                    for (int j = 0; j < 8; j++)
                    {
                        listbox[i + a * 4].Items.Add(strRGB[a] + "XXX");
                    }
                    groupBox1.Controls.Add(listbox[i + a * 4]);
                }
            }
        }
        private void AddValueText()
        {
            List<NumericUpDown[]> numUpDown = new List<NumericUpDown[]> { Rvalue, Gvalue, Bvalue };
            for (int a = 0; a < 3; a++)
            {
                for (int i = 0; i < 4; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        numUpDown[a][j + i * 8] = new System.Windows.Forms.NumericUpDown();
                        numUpDown[a][j + i * 8].Location = new System.Drawing.Point(50 + 95 * i, 15 + j * 21 + a * 170);
                        numUpDown[a][j + i * 8].Size = new System.Drawing.Size(40, 10);
                        numUpDown[a][j + i * 8].Maximum = 0xfff;
                        numUpDown[a][j + i * 8].Hexadecimal = true;
                        groupBox1.Controls.Add(numUpDown[a][j + i * 8]);
                    }
                }
            }
        }
        #endregion
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            {


                double Lr_d, Lg_d, Lb_d;
                int specFlag = 0;
                string[] arr = txtSpec.Lines;





                // btnReadWriteGamma_Clicked(btn_Gwrite, null);

                Thread.Sleep(60);
                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToDouble(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);

                            if (specFlag == 1)   //multi 时避免多次计算
                                break;
                            specFlag++;
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                        else if (line.Contains("__GAMMA_SET"))

                        {
                            gamma_set.Text = line.Substring(line.IndexOf("(") + 1, 1);
                        }
                    }

                    std_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                    std_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                    std_yoff.Text = Diven_Offset[0].Y_OFF.ToString();

                    Total_points = Diven_Gamma[0].Points_num;
                    if (Total_points == 27)
                        rb_27_point.Checked = Enabled;
                    else
                        rb_other_point.Checked = Enabled;
                    D_lums = new double[Total_points, 3];
                    D_lum = new double[Total_points];

                    std_gamma.Text = Diven_Gamma[0].Curve.ToString();
                    std_lum.Text = Diven_Gamma[0].Lum.ToString();
                    std_x.Text = Diven_Gamma[0].X.ToString();
                    std_y.Text = Diven_Gamma[0].Y.ToString();
                    for (int p = 0; p < Total_points; p++)
                    {   //Diven_Offset[p].NO 灰阶绑点                 
                        D_lum[p] = (Math.Pow((Diven_Offset[p].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                    }
                    CaSDKObj.YUV_to_RGB(Diven_Gamma[0].Y, Diven_Gamma[0].X, out Lr_d, out Lb_d, out Lg_d);//R/B/G分亮度转换
                    for (int i = 0; i < Total_points; i++)
                    {
                        D_lums[i, 0] = D_lum[i] * Lr_d; //R/B/G分亮度计算
                        D_lums[i, 1] = D_lum[i] * Lg_d;
                        D_lums[i, 2] = D_lum[i] * Lb_d;
                    }
                }
                catch
                {
                    File.Delete(@"c:\Users\Public\2KMainForm\GammaConfig");
                    error_flag++;
                    MessageBox.Show("格式输入有误!!");
                    return;
                }

            }
        }
        private void show_RGB_value(object sender, EventArgs e)
        {
            for (int i = 0; i < 32 - Total_points; i++)    //用不到的地方直接黑
            {
                if (Rvalue[31 - i].Enabled == true)
                {
                    Rvalue[31 - i].Enabled = false;
                    Rvalue[31 - i].BackColor = Color.Gray;
                    Gvalue[31 - i].Enabled = false;
                    Gvalue[31 - i].BackColor = Color.Gray;
                    Bvalue[31 - i].Enabled = false;
                    Bvalue[31 - i].BackColor = Color.Gray;
                }
            }
            for (int i = 0; i < Total_points; i++)     //交叉部分
            {
                if (Rvalue[i].Enabled == false)
                {
                    Rvalue[i].Enabled = true;
                    Gvalue[i].Enabled = true;
                    Bvalue[i].Enabled = true;
                    Rvalue[i].BackColor = Color.White;
                    Gvalue[i].BackColor = Color.White;
                    Bvalue[i].BackColor = Color.White;
                }
            }
            try
            {
                for (int a = 0; a < 3; a++)  //填充灰阶
                {
                    for (int i = 0; i < 4; i++)
                    {
                        listbox[i + a * 4].Items.Clear();

                        for (int j = 0; j < 8; j++)
                        {
                            if ((j + 8 * i) >= Diven_Gamma[0].Points_num)
                            { break; }
                            listbox[i + a * 4].Items.Add(strRGB[a] + Diven_Offset[Diven_Gamma[0].Points_num - 1 - (i * 8 + j)].NO.ToString());
                        }

                    }
                }
            }
            catch
            {

                for (int j = 0; j < 8; j++)
                {
                    listbox[0].Items.Add(strRGB[0] + "XXX");
                    error_flag++;
                }
                MessageBox.Show("关闭即将跳出的窗口，重新进入.....");
                return;

            }
        }
        private void open_txt_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "精度配置文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "gamma cfg write";

            if (of.ShowDialog() == DialogResult.OK)
            {
                txtSpec.Clear();
                //读取文本信息
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str_generate = streamReader.ReadLine();
                //循环读取文本信息
                while (str_generate != null)
                {
                    txtSpec.AppendText(str_generate + "\r\n");
                    str_generate = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
                btnCalculate_Click(null, null);
                get_reg_address();
                show_RGB_value(null, null);
            }
        }

        private void save_txt_Click(object sender, EventArgs e)
        {
            if (txtSpec.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
            }
            else
            {
                //创建保存对话框对象
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "gamma cfg files (*.txt)|*.txt"; //过滤文件类型
                save.FilterIndex = 1;
                save.RestoreDirectory = true;
                if (save.ShowDialog() == DialogResult.OK)
                {
                    string path = save.FileName;
                    save.DefaultExt = ".txt";
                    StreamWriter sw = new StreamWriter(path);
                    sw.WriteLine(txtSpec.Text);
                    sw.Close();
                }
            }
        }
        private void open_gamma_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            string strtmp = "";
            of.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*";
            of.Title = "打开Gamma文件";
            if (of.ShowDialog() == DialogResult.OK)
            //读取文本信息
            {
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string strLine = streamReader.ReadLine();
                //循环读取文本信息
                while (!string.IsNullOrEmpty(strLine))
                {
                    strtmp = strtmp + strLine + ",";
                    strLine = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                for (int i = 0; i < Total_points; i++)
                {
                    Rvalue[i].Text = arrtmp[1 + 6 * i].ToString();
                    Gvalue[i].Text = arrtmp[3 + 6 * i].ToString();
                    Bvalue[i].Text = arrtmp[5 + 6 * i].ToString();
                }
            }
        }
        private void save_gamma_Click(object sender, EventArgs e)
        {

            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "保存Gamma文件";
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                    for (int i = 0; i < Total_points; i++)
                    {

                        str = str + "R" + Diven_Offset[i].NO.ToString() + "," + Rvalue[i].Text + ","
                          + "G" + Diven_Offset[i].NO.ToString() + "," + Gvalue[i].Text + ","
                          + "B" + Diven_Offset[i].NO.ToString() + "," + Bvalue[i].Text + "\r\n";
                    }
                    sw.WriteLine(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Gamma保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Gamma保存时发生错误，请再试！", "系统提示：");
                }
            }
        } //
        private void btnReadWriteGamma_Clicked(object sender, EventArgs e)
        {

            ushort r = 0, g = 0, b = 0;
            Button btnTemp = (Button)sender;


            switch (btnTemp.Name)
            {

                case "btn_Gwrite":
                    {
                        DDIC_Reg_write(gammaPage_1[0]);
                        gammaSetSelect((int)gamma_set.Value);
                        //  get_reg_address();
                        Gamma_write_all(regType);
                    }
                    break;
                case "btn_RGBread":
                    {
                        DDIC_Reg_write(gammaPage_1[0]);
                        gammaSetSelect((int)gamma_set.Value);
                        Gamma_read_all(regType);
                    }
                    break;
                default:
                    break;
            }
        }
        static bool udc_flag = false;
        private void send_gamma_picture(bool udc_flag)
        {
            if (udc_flag)
            {

                btnPrevPic(1, 4, 1, 233, 67, 20, 50, Diven_Offset[index].NO);

            }
            else
            {
                string a = string.Format("{0:x2}", Convert.ToByte(Diven_Offset[index].NO));

                string gray = "ea," + a + "," + a + "," + a;
                DDIC_Reg_write("ff,f0");
                DDIC_Reg_write("f9,01");
                //   Thread.Sleep(60);
                DDIC_Reg_write("50,04");
                //     Thread.Sleep(60);
                DDIC_Reg_write("ff,25");
                //    Thread.Sleep(60);
                DDIC_Reg_write("e8,00,00,00,00,00,00,00,01");
                //    Thread.Sleep(60);
                DDIC_Reg_write("e9,00");
                //    Thread.Sleep(60);
                System.Diagnostics.Debug.Print("ea=" + gray);
                DDIC_Reg_write(gray);
                DDIC_Reg_write("eb,00");
                //    Thread.Sleep(60);
                DDIC_Reg_write("ec,01");

                regGray = "2f," + string.Format("{0:x2}", Convert.ToByte(Total_points - 1 - index) | 0x40);
                DDIC_Reg_write("ff,21");
                //     Thread.Sleep(60);
                DDIC_Reg_write(regGray);
                //      Thread.Sleep(60);
                DDIC_Reg_write("33,03");


            }

        }
        public int[] reg_alloc;
        byte[] send_buf_direct = new byte[179];
        private void get_send_buf_direct()
        {
            dateLeghth = 0;
            for (int i = 0; i < gamma_r.Length / 2; i++)
            {
                dateLeghth = dateLeghth + gamma_r[1 + 2 * i] + 2;
            }
            //  System.Diagnostics.Debug.Print(dateLeghth.ToString());
            //byte[] send_buf_direct = new byte[dateLeghth + 5];

            send_buf_direct[0] = 0x80;//NT38360
            send_buf_direct[1] = 0x05; //register normal gamma
            send_buf_direct[2] = (byte)(dateLeghth);

            byte[] tempR = new byte[currentRmapping.Length];
            byte[] tempG = new byte[currentRmapping.Length];
            byte[] tempB = new byte[currentRmapping.Length];
            byte[] temp_all = new byte[currentRmapping.Length * 3];
            //数据和寄存器值开始拼接+映射
            {
                for (int i = 0; i < Total_points; i++)
                {
                    tempR[currentRmapping[2 * i]] = Convert.ToByte((int)Rvalue[i].Value >> 8);
                    tempR[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Rvalue[i].Value & 0xff);
                    tempG[currentRmapping[2 * i]] = Convert.ToByte((int)Gvalue[i].Value >> 8);
                    tempG[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Gvalue[i].Value & 0xff);
                    tempB[currentRmapping[2 * i]] = Convert.ToByte((int)Bvalue[i].Value >> 8);
                    tempB[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Bvalue[i].Value & 0xff);
                }
                tempR.CopyTo(temp_all, 0);
                tempG.CopyTo(temp_all, currentRmapping.Length);
                tempB.CopyTo(temp_all, currentRmapping.Length * 2);
                List<byte> allList = new List<byte>(temp_all);
                int position1 = 0;
                for (int i = 0; i < gamma_r.Length / 2; i++)
                {
                    allList.Insert(0 + position1, (byte)(gamma_r[2 * i + 1] + 1));
                    allList.Insert(1 + position1, (byte)(gamma_r[2 * i]));
                    position1 = position1 + gamma_r[2 * i + 1] + 2;
                }
                for (int j = 0; j < currentRmapping.Length * 3 + gamma_r.Length; j++)
                {
                    send_buf_direct[3 + j] = allList[j];
                }
            }
        }
        private void adjust_direct(int index, int r, int g, int b)
        {

            if (Total_points - index - 1 >= 24)
            {
                send_buf_direct[5 + 3 * 18] = Convert.ToByte(r >> 8);
                send_buf_direct[5 + 3 * 18 + 1] = Convert.ToByte(r & 0xff);

                send_buf_direct[5 + 6 * 18 + 4] = Convert.ToByte(g >> 8);
                send_buf_direct[5 + 6 * 18 + 5] = Convert.ToByte(g & 0xff);

                send_buf_direct[5 + 9 * 18 + 8] = Convert.ToByte(b >> 8);
                send_buf_direct[5 + 9 * 18 + 9] = Convert.ToByte(b & 0xff);

            }
            else if (Total_points - index - 1 >= 16)
            {
                send_buf_direct[3 + 2 + 18 * 2 + 2 * (Total_points - index - 16 - 1)] = Convert.ToByte(r >> 8);
                send_buf_direct[3 + 2 + 18 * 2 + 2 * (Total_points - index - 16 - 1) + 1] = Convert.ToByte(r & 0xff);

                send_buf_direct[3 + 2 + 5 * 18 + 4 + 2 * (Total_points - index - 16 - 1)] = Convert.ToByte(g >> 8);
                send_buf_direct[3 + 2 + 5 * 18 + 4 + 2 * (Total_points - index - 16 - 1) + 1] = Convert.ToByte(g & 0xff);

                send_buf_direct[3 + 2 + 8 * 18 + 8 + 2 * (Total_points - index - 16 - 1)] = Convert.ToByte(b >> 8);
                send_buf_direct[3 + 2 + 8 * 18 + 8 + 2 * (Total_points - index - 16 - 1) + 1] = Convert.ToByte(b & 0xff);
            }
            else if (Total_points - index - 1 >= 8)
            {
                send_buf_direct[3 + 2 + 18 + 2 * (Total_points - index - 8 - 1)] = Convert.ToByte((r >> 8));
                send_buf_direct[3 + 2 + 18 + 2 * (Total_points - index - 8 - 1) + 1] = Convert.ToByte(r & 0xff);

                send_buf_direct[3 + 2 + 4 * 18 + 4 + 2 * (Total_points - 8 - index - 1)] = Convert.ToByte((g >> 8));
                send_buf_direct[3 + 2 + 4 * 18 + 4 + 2 * (Total_points - 8 - index - 1) + 1] = Convert.ToByte(g & 0xff);

                send_buf_direct[3 + 2 + 7 * 18 + 8 + 2 * (Total_points - 8 - index - 1)] = Convert.ToByte((b >> 8));
                send_buf_direct[3 + 2 + 7 * 18 + 8 + 2 * (Total_points - 8 - index - 1) + 1] = Convert.ToByte(b & 0xff);

            }
            else
            {
                send_buf_direct[3 + 2 + 2 * (Total_points - index - 1)] = Convert.ToByte((r >> 8) & 0xff);
                send_buf_direct[3 + 2 + 2 * (Total_points - index - 1) + 1] = Convert.ToByte(r & 0xff);

                send_buf_direct[3 + 2 + 3 * 18 + 4 + 2 * (Total_points - index - 1)] = Convert.ToByte((g >> 8) & 0xff);
                send_buf_direct[3 + 2 + 3 * 18 + 4 + 2 * (Total_points - index - 1) + 1] = Convert.ToByte(g & 0xff);

                send_buf_direct[3 + 2 + 6 * 18 + 8 + 2 * (Total_points - index - 1)] = Convert.ToByte((b >> 8) & 0xff);
                send_buf_direct[3 + 2 + 6 * 18 + 8 + 2 * (Total_points - index - 1) + 1] = Convert.ToByte(b & 0xff);
            }
            CRCData.CalculateCrc16(send_buf_direct, out send_buf_direct[dateLeghth + 5 - 2], out send_buf_direct[dateLeghth + 5 - 1]);
            try
            {
                frmHelp.comPort.Write(send_buf_direct, 0, dateLeghth + 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        private void btnAutoGammas_Click(object sender, EventArgs e)
        {
            index = 0;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;

            //if (NT37350_AOD_Inter_cbx.Checked == true)  //AOD gamma adjust in AOD mode or not
            //{
            //    Load_GammmPic(Diven_Offset[index].NO.ToString()); //Load pic
            //}
            //else
            //
            gray_label.Text = Diven_Offset[index].NO.ToString();
            //frmHelp.numPatternG.Value = Diven_Offset[index].NO;
            //frmHelp.numPatternB.Value = Diven_Offset[index].NO;
            Application.DoEvents();
            send_gamma_picture(udc_flag);
            // frmHelp.OLED_Show_Click(frmHelp.btnwhite, e);
            DDIC_Reg_write(gammaPage_1[0]);
            gammaSetSelect((int)gamma_set.Value);
            get_send_buf_direct();
            Thread.Sleep(200);
            if (udc_flag)
                T20.Interval = 300;
            else
                T20.Interval = 300;
            T20.Enabled = true;

        }
        private void T20_Tick(object sender, EventArgs e)
        {
            Adjust_gamma(null, null);
        }
        string rReg, gReg, bReg, regGray;
        private void bist_mode_out()
        {
            DDIC_Reg_write("ff,f0");
            DDIC_Reg_write("50,00");  //out tune mode
            DDIC_Reg_write("ff,25");
            DDIC_Reg_write("ec,00");   //out bist
            DDIC_Reg_write("ff,21");
            DDIC_Reg_write("2f,00");     //out node select
            DDIC_Reg_write("33,01");   //out display
        }
        private void Adjust_gamma(Object myObject, EventArgs e)
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;

            // frmHelp.Msr_CASDK();
            CA410_Measure_Lxy_38360();
            if (Gamma_adjust_timeout_flag == true)//如果是0绑点
            {
                flag1 = 0;
                flag2 = 0;
                flag3 = 0;
            }
            else
            {
                if ((Lv2 < (D_lum[index] + D_lum[index] * Diven_Offset[index].LUM_OFF / 100)) && (Lv2 > (D_lum[index] - D_lum[index] * Diven_Offset[index].LUM_OFF / 100)))//G
                { flag1 = 0; }
                else
                { flag1 = 1; }
                if ((sx2 < (Diven_Gamma[0].X + Diven_Offset[index].X_OFF)) && (sx2 > (Diven_Gamma[0].X - Diven_Offset[index].X_OFF)) && flag1 == 0)//R
                { flag3 = 0; }
                else
                { flag3 = 1; }
                if ((sy2 < (Diven_Gamma[0].Y + Diven_Offset[index].Y_OFF)) && (sy2 > (Diven_Gamma[0].Y - Diven_Offset[index].Y_OFF)) && flag1 == 0 && flag3 == 0)//B
                { flag2 = 0; }
                else
                { flag2 = 1; }
                //if ((frmHelp.CASDK_LUM < (D_lum[index] + D_lum[index] * Diven_Offset[index].LUM_OFF / 100)) && (frmHelp.CASDK_LUM > (D_lum[index] - D_lum[index] * Diven_Offset[index].LUM_OFF / 100)))//G
                //{ flag1 = 0; }
                //else
                //{ flag1 = 1; }
                //if ((frmHelp.CASDK_x < (Diven_Gamma[0].X + Diven_Offset[index].X_OFF)) && (frmHelp.CASDK_x > (Diven_Gamma[0].X - Diven_Offset[index].X_OFF)) && flag1 == 0)//R
                //{ flag3 = 0; }
                //else
                //{ flag3 = 1; }
                //if ((frmHelp.CASDK_y < (Diven_Gamma[0].Y + Diven_Offset[index].Y_OFF)) && (frmHelp.CASDK_y > (Diven_Gamma[0].Y - Diven_Offset[index].Y_OFF)) && flag1 == 0 && flag3 == 0)//B
                //{ flag2 = 0; }
                //else
                //{ flag2 = 1; }

            }
            if (flag1 == 0 && flag2 == 0 && flag3 == 0)
            {
                T20.Enabled = false;
                //reset-----
                Gamma_adjust_timeout_flag = false;
                frmHelp.Gamma_auto_adjust_count = 0;
                //--------
                index++;

                if (index == Total_points - 1)
                {
                    frmHelp.textBox1.Text = frmHelp.textBox1.Text + "gamma调试完毕!\r\n";
                    btnReadWriteGamma_Clicked(btn_Gwrite, null);
                    if (!udc_flag)
                        bist_mode_out();
                    //---------------------------------add-------------------------------------
                    if (Multi_gamma_txt_next_index < Multi_gamma_txt_line_count)
                    {
                        Multi_gamma_txt_now_index = Multi_gamma_txt_next_index;
                        Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
                    }
                    //---------------------------------add-------------------------------------
                }
                if (index < Total_points - 1)
                {
                    //if (NT37350_AOD_Inter_cbx.Checked == true)  //AOD gamma adjust in AOD mode or not
                    //{
                    //    Load_GammmPic(Diven_Offset[index].NO.ToString()); //Load pic
                    //}
                    //else
                    //{
                    gray_label.Text = Diven_Offset[index].NO.ToString();
                    //frmHelp.numPatternR.Value = Diven_Offset[index].NO;//固定255灰阶
                    //frmHelp.numPatternG.Value = Diven_Offset[index].NO;
                    //frmHelp.numPatternB.Value = Diven_Offset[index].NO;
                    Application.DoEvents();
                    send_gamma_picture(udc_flag);
                    // frmHelp.OLED_Show_Click(frmHelp.btnPatternW, null);//写入Pattern参数

                    Thread.Sleep(500); //1秒=1000毫秒，
                    T20.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }
            }
            else  //进入调试步骤
            {
                decimal r = 0, g = 0, b = 0;
                //CaSDKObj.YUV_to_RGB(frmHelp.CASDK_y, frmHelp.CASDK_x, out Lr_t, out Lb_t, out Lg_t);
                //lumr = frmHelp.CASDK_LUM * Lr_t;
                //lumg = frmHelp.CASDK_LUM * Lg_t;
                //lumb = frmHelp.CASDK_LUM * Lb_t;
                CaSDKObj.YUV_to_RGB(sy2, sx2, out Lr_t, out Lb_t, out Lg_t);
                lumr = Lv2 * Lr_t;
                lumg = Lv2 * Lg_t;
                lumb = Lv2 * Lb_t;

                try
                {
                    frmHelp.Gamma_auto_adjust_count_set = 50;
                    if (index == Total_points - 1)
                    {
                        Rvalue[Total_points - 1 - index].Value = 0;
                        Gvalue[Total_points - 1 - index].Value = 0;
                        Bvalue[Total_points - 1 - index].Value = 0;
                        r = 0;
                        g = 0;
                        b = 0;
                        // frmHelp.auto_gamma_write(gamma_r[Diven_Gamma[0].Points_num - 1 - index], 0, gamma_g[Diven_Gamma[0].Points_num - 1 - index], 0, gamma_b[Diven_Gamma[0].Points_num - 1 - index], 0);
                        Gamma_adjust_timeout_flag = true;
                    }
                    else
                    {
                        frmHelp.Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], Rvalue[Total_points - index - 1].Value, Gvalue[Total_points - index - 1].Value, Bvalue[Total_points - index - 1].Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                        Rvalue[Total_points - index - 1].Value = r;
                        Gvalue[Total_points - index - 1].Value = g;
                        Bvalue[Total_points - index - 1].Value = b;

                        if (Gvalue[Total_points - index - 1].Value < Gvalue[Total_points - index - 2].Value)
                        {
                            Rvalue[Total_points - index - 2].Value = r - 0x10;
                            Gvalue[Total_points - index - 2].Value = g - 0x10;
                            Bvalue[Total_points - index - 2].Value = b - 0x10;
                        }
                    }
                    if (regType == 0)
                    {
                        //Auto_gamma_write(gamma_r[Total_points - 1 - index], (ushort)r, gamma_g[Total_points - 1 - index], (ushort)g, gamma_b[Total_points - 1 - index], (ushort)b);
                    }
                    else if (regType == 1)
                    {
                        if (udc_flag)
                        {

                            adjust_direct(index, (int)r, (int)g, (int)b);
                            // btnReadWriteGamma_Clicked//(btn_Gwrite, null);
                            Application.DoEvents();
                            //   Thread.Sleep(150);

                        }
                        else
                        {
                            rReg = "30," + string.Format("{0:x2}", Convert.ToByte((int)r >> 8)) + "," + string.Format("{0:x2}", Convert.ToByte((int)r & 0xff));
                            gReg = "31," + string.Format("{0:x2}", Convert.ToByte((int)g >> 8)) + "," + string.Format("{0:x2}", Convert.ToByte((int)g & 0xff));
                            bReg = "32," + string.Format("{0:x2}", Convert.ToByte((int)b >> 8)) + "," + string.Format("{0:x2}", Convert.ToByte((int)b & 0xff));

                            //System.Diagnostics.Debug.Print("tt=" + (Total_points - 1 - index).ToString());
                            //System.Diagnostics.Debug.Print(rReg);
                            //System.Diagnostics.Debug.Print(gReg);
                            //System.Diagnostics.Debug.Print(bReg);

                            // btnReadWriteGamma_Clicked(btn_Gwrite, null);

                            DDIC_Reg_write(rReg);

                            DDIC_Reg_write(gReg);

                            DDIC_Reg_write(bReg);
                            //  Thread.Sleep(60);
                            //    System.Diagnostics.Debug.Print(regGray);
                        }
                    }
                }
                catch
                {
                    T20.Enabled = false;
                    MessageBox.Show("调整数值超限");
                }
            }
        }
        private void Auto_gamma_write(UInt16 addr, UInt16 datar, UInt16 addg, UInt16 datag, UInt16 addb, UInt16 Datab)//一组gamma写入
        {
            byte[] Send_buf = new byte[18];
            Setting.TempRecord.cmdLen = 17;

            Send_buf[0] = 0x80;//NT38360

            {
                Send_buf[1] = 0x04; //register normal gamma
            }          //{
                       //    Send_buf[1] = 0xDD; //register 
                       //}
            Send_buf[2] = 13; //length

            Send_buf[3] = Convert.ToByte(addr >> 8);
            Send_buf[4] = Convert.ToByte(datar >> 8);
            Send_buf[5] = Convert.ToByte(addr & 0xff);
            Send_buf[6] = Convert.ToByte(datar & 0xff);
            Send_buf[7] = Convert.ToByte(addg >> 8);
            Send_buf[8] = Convert.ToByte(datag >> 8);
            Send_buf[9] = Convert.ToByte(addg & 0xff);
            Send_buf[10] = Convert.ToByte(datag & 0xff);
            Send_buf[11] = Convert.ToByte(addb >> 8);
            Send_buf[12] = Convert.ToByte(Datab >> 8);
            Send_buf[13] = Convert.ToByte(addb & 0xff);
            Send_buf[14] = Convert.ToByte(Datab & 0xff);
            {
                Send_buf[15] = Convert.ToByte(0);
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[16], out Send_buf[17]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 18);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            T20.Enabled = false;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
        }
        private int Multi_gamma_txt_now_index = 0;
        private int Multi_gamma_txt_next_index;
        private int Multi_gamma_txt_line_count = 0;
        private int Multi_gamma_group_index = 0;
        private void btn_flexible_gamma_Click(object sender, EventArgs e)
        {
            Multi_gamma_txt_now_index = 0;
            Multi_gamma_txt_line_count = this.txtSpec.Lines.GetUpperBound(0);
            Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
        }
        private void Multi_flexible_gammas(int txt_index, out int list_view_index)
        {
            string strLine = Convert.ToString(txtSpec.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组
            string perline = string.Empty;
            string perline0 = string.Empty;
            list_view_index = 0;
            if (txtSpec.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
            }
            else  //标记关键事件
            {
                try
                {
                    arr = strLine.Split('\n'); //以逗号分割，添加到数
                    for (int i = txt_index; i < arr.Length;)  //获取的行数
                    {
                        perline = arr[i];
                        perline = perline.Replace(" ", "");
                        perline = perline.Replace(".", "");
                        perline = perline.Replace(";", "");
                        perline = perline.Replace("(", "");
                        perline = perline.Replace(")", "");
                        perline = perline.Replace("\r", "");

                        if (perline.Contains("REGW"))
                        {
                            perline = perline.Replace("REGW", "");
                            frmHelp.Gen_BC_lab.Text = perline;
                            frmHelp.Generate_File_Click(frmHelp.Gen_DBC_control, null);
                            Thread.Sleep(100);
                            i = i + 1;
                        }
                        else if (perline.Contains("EXIST"))
                        {
                            existGamma();
                            Thread.Sleep(100);
                            i = i + 1;
                        }
                        else if (perline.Contains("UDC"))
                        {
                            udc_flag = true;
                            Thread.Sleep(100);
                            i = i + 1;
                        }
                        else if (perline.Contains("NORMAL"))
                        {
                            udc_flag = false;
                            Thread.Sleep(100);
                            i = i + 1;
                        }
                        else if (perline.Contains("ENTER"))
                        {
                            gammaPiontSet();
                            Thread.Sleep(100);
                            i = i + 1;
                        }
                        else if (perline.Contains("SAVE"))
                        {
                            string pathsave_file = System.Environment.CurrentDirectory + "\\l_gamma";
                            if (Directory.Exists(pathsave_file) == false)
                            {
                                Directory.CreateDirectory(pathsave_file);
                            }
                            string pathsave = System.Environment.CurrentDirectory + "\\l_gamma" + "\\gamma" + Multi_gamma_group_index.ToString() + ".csv";
                            Multi_SaveGamma(pathsave);
                            Thread.Sleep(50);
                            i = i + 1;
                        }
                        else if (perline.Contains("GAMMA_SET"))
                        {
                            perline = perline.Replace("GAMMA_SET", "");
                            perline = perline.Replace("_", "");
                            Multi_gamma_group_index = Convert.ToInt32(perline);
                            currentGammaSet = Multi_gamma_group_index;

                            gamma_set.Value = currentGammaSet;
                            gammaSetSelect(currentGammaSet);
                            get_reg_address();                     //jiao 重要
                            System.Collections.ArrayList list = new System.Collections.ArrayList();
                            do
                            {
                                i = i + 1;
                                perline = arr[i];
                                list.Add(perline + "\n");
                            } while (perline.Contains("GAMMA_TUNING") == false);
                            string[] gamma_set_lines = (string[])list.ToArray(typeof(string));
                            Text_Processing(gamma_set_lines);
                            try
                            {
                                string pathsave_file = System.Environment.CurrentDirectory + "\\l_gamma";
                                if (Directory.Exists(pathsave_file) == false)
                                {
                                    Directory.CreateDirectory(pathsave_file);
                                }
                                string pathload = System.Environment.CurrentDirectory + "\\l_gamma" + "\\gamma" + Multi_gamma_group_index.ToString() + ".csv";
                                Multi_LoadGamma(pathload);
                                get_send_buf_direct();
                                Application.DoEvents();
                                //btnReadWriteGamma_Clicked(btn_Gwrite, null);
                                Thread.Sleep(15);

                            }
                            catch {; }
                            btnAutoGammas_Click(null, null); //替换成相应IC的自动gamma启动函数名
                            list_view_index = i;
                            break;
                        }
                        else
                        {
                            i = i + 1;
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("输入格式有误！");
                }
            }
        }

        private void Multi_LoadGamma(string path)
        {
            string strtmp = "";
            //读取文本信息
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            string strLine = streamReader.ReadLine();
            //循环读取文本信息
            while (!string.IsNullOrEmpty(strLine))
            {
                strtmp = strtmp + strLine + ",";
                strLine = streamReader.ReadLine(); //循环读取下一行
            }
            fs.Close(); //关闭流
            streamReader.Close();
            string[] arrtmp = strtmp.Split(new Char[] { ',' });
            for (int i = 0; i < Total_points; i++)
            {
                Rvalue[i].Text = arrtmp[1 + 6 * i].ToString();
                Gvalue[i].Text = arrtmp[3 + 6 * i].ToString();
                Bvalue[i].Text = arrtmp[5 + 6 * i].ToString(); ;

            }
        }
        private void Text_Processing(string[] txt_path)
        {
            double Lr_d, Lg_d, Lb_d;
            string[] arr = txt_path;
            {
                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToDouble(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
            }
            try  //获取调整spec
            {
                std_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                std_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                std_yoff.Text = Diven_Offset[0].Y_OFF.ToString();


                D_lums = new double[Total_points, 3];
                D_lum = new double[Total_points];

                std_gamma.Text = Diven_Gamma[0].Curve.ToString();
                std_lum.Text = Diven_Gamma[0].Lum.ToString();
                std_x.Text = Diven_Gamma[0].X.ToString();
                std_y.Text = Diven_Gamma[0].Y.ToString();

                for (int p = 0; p < Total_points; p++)
                {   //Diven_Offset[p].NO 灰阶绑点                 
                    D_lum[p] = (Math.Pow((Diven_Offset[p].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                }

                CaSDKObj.YUV_to_RGB(Diven_Gamma[0].Y, Diven_Gamma[0].X, out Lr_d, out Lb_d, out Lg_d);//R/B/G分亮度转换

                for (int i = 0; i < Total_points; i++)
                {
                    D_lums[i, 0] = D_lum[i] * Lr_d; //R/B/G分亮度计算
                    D_lums[i, 1] = D_lum[i] * Lg_d;
                    D_lums[i, 2] = D_lum[i] * Lb_d;
                }
            }
            catch
            {
                MessageBox.Show("格式输入有误");
            }
        }
        private void Multi_SaveGamma(string path)
        {
            string str = "保存Gamma文件";
            StreamWriter sw = null; //文件流
            sw = new StreamWriter(path, false, Encoding.UTF8);
            for (int i = 0; i < Total_points; i++)
            {

                str = str + "R" + Diven_Offset[i].NO.ToString() + "," + Rvalue[i].Text + ","
                  + "G" + Diven_Offset[i].NO.ToString() + "," + Gvalue[i].Text + ","
                  + "B" + Diven_Offset[i].NO.ToString() + "," + Bvalue[i].Text + "\r\n";
            }
            sw.WriteLine(str);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        } //
        private void RM692E1_Load(object sender, EventArgs e)
        {
            string Config_path = @"c:\Users\Public\2KMainForm\GammaConfig";
            //  FileInfo cfg = new FileInfo(Config_path);
            flow_list.Text =
                        "ICWRITE\r\n" +
                        "ff,10\r\n" +
                        "69,01\r\n" +
                        "LOAD\r\n" +
                        "ff,10\r\n" +
                        "69,00\r\n" +
                        "FF,2C\r\n" +
                        "50,13\r\n" +
                        "51,1B\r\n" +
                        "52,20\r\n" +
                        "53,80\r\n" +
                        "54,20\r\n" +
                        "55,80\r\n" +
                        "56,70\r\n" +
                        "57,77\r\n" +
                        "58,E0\r\n" +
                        "59,E0\r\n" +
                        "5A,E0\r\n" +
                        "5B,10\r\n" +
                        "5C,10\r\n" +
                        "5D,10\r\n" +
                        "5E,E0\r\n" +
                        "5F,E0\r\n" +
                        "60,E0\r\n" +
                        "61,10\r\n" +
                        "62,10\r\n" +
                        "63,10\r\n" +
                        "64,0F\r\n" +
                        "65,0F\r\n" +
                        "66,0F\r\n" +
                        "67,0F\r\n" +
                        "68,0F\r\n" +
                        "69,0F\r\n" +
                        "6A,02\r\n" +
                        "6B,04\r\n" +
                        "6E,06\r\n" +
                        "6F,03\r\n" +
                        "70,05\r\n" +
                        "71,07\r\n" +
                        "72,03\r\n" +
                        "73,05\r\n" +
                        "74,07\r\n" +
                        "75,04\r\n" +
                        "76,06\r\n" +
                        "77,08\r\n" +
                        "78,04\r\n" +
                        "79,06\r\n" +
                        "7A,08\r\n" +
                        "7B,05\r\n" +
                        "7C,07\r\n" +
                        "7D,09\r\n" +
                        "7E,10\r\n" +
                        "7F,00\r\n" +
                        "80,D4\r\n" +
                        "81,FF\r\n" +
                        "82,2E\r\n" +
                        "83,59\r\n" +
                        "84,88\r\n" +
                        "85,88\r\n" +
                        "86,88\r\n" +
                        "87,88\r\n" +
                        "88,88\r\n" +
                        "89,88\r\n" +
                        "//CRC\r\n" +
                        "//CRC\r\n" +
                        "FF,2C\r\n" +
                        "ICREAD\r\n" +
                        "F2,08\r\n";

            if (!File.Exists(Config_path))
            {
                //  MessageBox.Show("cfg is not exist");
            }
            else
            {
                StreamReader sr = new StreamReader(Config_path, Encoding.UTF8);
                string tmp = "";

                for (; ; )
                {
                    tmp = sr.ReadLine();
                    if (tmp == null)
                        break;
                    //if(tmp.Contains("regType"))
                    //{
                    //    regType = Convert.ToInt16( tmp.Substring(tmp.IndexOf("=")+1,1));
                    //    System.Diagnostics.Debug.Print("reg:"+regType.ToString());
                    //}
                    //else if(tmp.Contains("Total_points"))
                    //{
                    //    Total_points = Convert.ToInt16(tmp.Substring(tmp.IndexOf("=")+1, 2));
                    //    total_point_show.Text = Total_points.ToString();
                    //}
                    if (tmp.Contains("gamma_set"))
                    {
                        txtSpec.Clear();
                        for (; ; )
                        {
                            tmp = sr.ReadLine();
                            if (tmp.Contains("gamma_set"))
                            {
                                break;
                            }
                            else
                            {
                                txtSpec.AppendText(tmp + "\r\n");
                            }
                        }
                    }
                    else if (tmp.Contains("gamma_r"))
                    {
                        string[] gamma_regR = sr.ReadLine().Split(',');
                        System.Diagnostics.Debug.Print("leght=" + gamma_regR.Length.ToString());
                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_r[i] = Convert.ToUInt16(gamma_regR[i], 16);
                            System.Diagnostics.Debug.Print(String.Format("{0:X4}", gamma_r[i]));
                        }
                    }
                    else if (tmp.Contains("gamma_r"))
                    {
                        string[] gamma_regR = sr.ReadLine().Split(',');
                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_r[i] = Convert.ToUInt16(gamma_regR[i], 16);
                            System.Diagnostics.Debug.Print(String.Format("{0:X4}", gamma_r[i]));
                        }
                    }
                    else if (tmp.Contains("gamma_g"))
                    {
                        string[] gamma_regG = sr.ReadLine().Split(',');
                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_g[i] = Convert.ToUInt16(gamma_regG[i], 16);
                        }
                    }
                    else if (tmp.Contains("gamma_b"))
                    {
                        string[] gamma_regB = sr.ReadLine().Split(',');

                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_b[i] = Convert.ToUInt16(gamma_regB[i], 16);

                        }
                    }
                    else if (tmp.Contains("end"))
                    {
                        System.Diagnostics.Debug.Print("readfinished!");
                        sr.Close();

                        break;
                    }
                    System.Diagnostics.Debug.Print(tmp);
                }
            }
            btnCalculate_Click(null, null);
            get_reg_address();
            show_RGB_value(null, null);
        }
        private void save_current_cfg(object sender, FormClosedEventArgs e)
        {
            if (error_flag != 0)
            {
                return;
            }
            string Config_path = @"c:\Users\Public\2KMainForm\GammaConfig";

            StreamWriter sw = new StreamWriter(Config_path, false, Encoding.UTF8);
            sw.WriteLine("regType=" + regType.ToString());
            sw.WriteLine("Total_points=" + Total_points.ToString());
            sw.WriteLine("[gamma_set]");
            sw.WriteLine(txtSpec.Text);
            string tempR = "";
            string tempG = "";
            string tempB = "";
            if (regType == 0)
            {
                for (int i = 0; i < Total_points; i++)
                {
                    if (i == Total_points - 1)
                    {
                        tempR = tempR + String.Format("{0:X4}", gamma_r[i]);
                        tempG = tempG + String.Format("{0:X4}", gamma_g[i]);
                        tempB = tempB + String.Format("{0:X4}", gamma_b[i]);
                    }
                    else
                    {
                        tempR = tempR + String.Format("{0:X4}", gamma_r[i]) + ",";
                        tempG = tempG + String.Format("{0:X4}", gamma_g[i]) + ",";
                        tempB = tempB + String.Format("{0:X4}", gamma_b[i]) + ",";
                    }
                }
            }

            sw.WriteLine("[gamma_set]");
            sw.WriteLine("[gamma_r]");
            sw.WriteLine(tempR);
            sw.WriteLine("[gamma_g]");
            sw.WriteLine(tempG);
            sw.WriteLine("[gamma_b]");
            sw.WriteLine(tempB);
            sw.WriteLine("[end]");
            sw.Close();
        }
        private string Demura_defaultfilePath = "";
        private void btnReload_Demura_File_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择

            if (Demura_defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                dialog.SelectedPath = Demura_defaultfilePath;
            }
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //记录选中的目录
                Demura_defaultfilePath = dialog.SelectedPath;
                tBx_Demura_Bin_Path.Text = Demura_defaultfilePath;
            }
            if (!Directory.Exists(tBx_Demura_Bin_Path.Text))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            listBox3_Demura_File.Items.Clear();
            string s = null;
            DirectoryInfo d = new DirectoryInfo(tBx_Demura_Bin_Path.Text);
            FileInfo[] Files = d.GetFiles("*.*");//*.hex|
            // List<string> lstr = new List<string>();

            foreach (FileInfo file in Files)
            {
                s = file.Name.ToLower();
                if (s.EndsWith(".hex") || s.EndsWith(".dsc") || s.EndsWith(".bin") || s.EndsWith(".bmp") || s.EndsWith(".txt"))
                {
                    listBox3_Demura_File.Items.Add(s);
                }
            }
        }
        private void tBx_Demura_Bin_Path_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string path = tBx_Demura_Bin_Path.Text;

                if (!Directory.Exists(path))
                {
                    MessageBox.Show("文件夹不存在.");
                    return;
                }
                listBox3_Demura_File.Items.Clear();
                string s = null;
                DirectoryInfo d = new DirectoryInfo(path);
                FileInfo[] Files = d.GetFiles("*.*");//*.hex|
                                                     // List<string> lstr = new List<string>();

                foreach (FileInfo file in Files)
                {
                    s = file.Name.ToLower();
                    if (s.EndsWith(".hex") || s.EndsWith(".dsc") || s.EndsWith(".bin") || s.EndsWith(".bmp"))
                    {
                        listBox3_Demura_File.Items.Add(s);
                    }
                }
                tBx_Demura_Bin_Path.Text = path;
            }
        }
        public void Load_Demura_data_Click(object sender, EventArgs e)
        {
            Int32 m_txlen = 0;
            Int32 Once_txlen = 0;
            Int32 File_Length, File_Length_tep;
            bool tx_en = true;
            byte[] TemFileContent = new byte[1024 * 100];
            char[] Acsii_array = new char[2];
            Int32 div = 0;
            frmMain.frmain.textBox1.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "开始刷填 \r\n";
            div = Convert.ToInt16(frmMain.frmain.HACT.Value) * 3;
            TemFileContent[0] = 0x5B;
            TemFileContent[1] = 0xff;
            System.Int32 ByteReaded = 0x00;
            if (tBx_Demura_Bin_Path.Text == "")
            {
                MessageBox.Show("空文件夹");
                return;
            }

            string FileName = tBx_Demura_Bin_Path.Text + '\\' + listBox3_Demura_File.SelectedItem.ToString();
            FileStream aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            File_Length = Convert.ToInt32(aFile.Length);
            try
            { //Demura 告诉下位机Demura数据搬运开始
                TemFileContent[2] = 0xbd;
                TemFileContent[3] = 0xcf;
                TemFileContent[4] = 0xfc;
                TemFileContent[5] = 0xac;
                TemFileContent[6] = 0xca;
                TemFileContent[7] = Convert.ToByte(File_Length >> 24);
                TemFileContent[8] = Convert.ToByte((File_Length >> 16) & 0xff);
                TemFileContent[9] = Convert.ToByte((File_Length >> 8) & 0xff);
                TemFileContent[10] = Convert.ToByte(File_Length & 0xff);
                frmMain.frmain.comPort.Write(TemFileContent, 0, 11);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                tx_en = false;
                return;
            }
            //00000000000000000000000000000000000000
            //******add by chenfeng 20190124 if synapic demura data %256 equal to 0, please add 256 byte!
            //if (frmMain.frmain.IC_comboBox.SelectedIndex == Setting.Demura_Type.R66455_GM820 || frmMain.frmain.IC_comboBox.SelectedIndex == Setting.Demura_Type.R66456_GM825)
            //{
            //    if (File_Length % 256 == 0)
            //    {
            //        File_Length = File_Length + 256;
            //        //******add by chenfeng 20190124 if synapic demura data %256 equal to 0, please add 256 byte!
            //    }
            //}
            File_Length_tep = File_Length;

            while (tx_en)
            {
                if (File_Length_tep > (File_Length % div))
                {
                    Once_txlen = div;
                }
                else  //最后一笔
                {
                    Once_txlen = Convert.ToInt32(File_Length % div);
                    tx_en = false;
                }
                aFile.Seek(0 + m_txlen, SeekOrigin.Begin);    //跳转
                ByteReaded = aFile.Read(TemFileContent, 0, Once_txlen); // 存入第0位
                try
                {

                    frmMain.frmain.comPort.Write(TemFileContent, 0, Once_txlen + 0);
                    //Thread.Sleep(5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    tx_en = false;
                    break;
                }
                //tx_en = false;
                m_txlen += ByteReaded;
                progressBar2.Value = Convert.ToInt32((double)m_txlen / File_Length * 100);
                label_flash.Text = progressBar2.Value.ToString() + "%";
                Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                File_Length_tep = File_Length_tep - div;
            }

            try
            {
                frmMain.frmain.textBox1.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "载入完成... \r\n";
                aFile.Close();
            }
            catch
            {
                MessageBox.Show("请选择文件夹", "错误");
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            Load_Demura_data_Click(null, null);
        }
        private void load_demura_flow_txt_Click(object sender, EventArgs e)
        {
            flow_list.Text = "";
            OpenFileDialog of = new OpenFileDialog();
            if (of.ShowDialog() == DialogResult.OK)
            {
                if (of.FileName == "")
                {
                    MessageBox.Show("空文件夹");
                    return;
                }
                else
                {
                    FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    string temp = sr.ReadToEnd();

                    temp = temp.ToUpper();
                    temp = temp.Replace("\r\n", "$");
                    string[] arr = temp.Split('$');


                    for (int i = 0; i < arr.Length; i++)
                    {
                        arr[i] = arr[i].Trim();

                        if (arr[i] != "")
                            if (i == arr.Length - 1)
                                flow_list.Text += arr[i];
                            else
                                flow_list.Text += arr[i] + "\r\n";

                    }

                    sr.Close();
                    fs.Close();

                }
            }
        }
        private void save_demura_flow_txt_Click(object sender, EventArgs e)
        {
            string path = "";
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = @"(*.*)|*.txt";
            if (sf.ShowDialog() == DialogResult.OK)
            {
                path = sf.FileName;
            }
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine(flow_list.Text);
                sw.Close();
            }
        }

        private void one_key_demura_flow_Click(object sender, EventArgs e)
        {
            int statusFlag = 0;
            int previousFlag = 0;
            string all = flow_list.Text;
            all = all.Replace("\n", "$");
            string[] arr = all.Split('$');

            for (int i = 0; i < arr.Length; i++)
            {
                {
                    Regex b = new Regex(@"[[]|[]]|[ ]|(?<=//).+|[//]");
                    string str = b.Replace(arr[i], "");
                    str = str.Replace("-", ","); ;

                    if (str == "ICWRITE")
                        statusFlag = 1;
                    else if (str == "ICREAD")
                        statusFlag = 2;
                    else if (str.Contains("DELAY") && str.Length != 5)
                    {
                        if (str.Contains("DELAYMS"))
                        {
                            str = str.Substring(7);
                        }
                        else
                        {
                            str = str.Substring(5);
                        }
                        Thread.Sleep(Convert.ToInt16(str));
                        log_txt.Text += "delay:" + str + "\r\n";
                    }
                    else if (str.Contains("DELAY") && str.Length == 5)
                    {
                        previousFlag = statusFlag;
                        statusFlag = 3;

                    }
                    else if (str == "LOAD")
                    {
                        Load_Demura_data_Click(null, null);
                    }
                    else
                    {
                        switch (statusFlag)
                        {
                            case 1:
                                {
                                    DDIC_Reg_write(str);
                                    for (int j = 0; j < 100000; j++)
                                    {
                                        Application.DoEvents();
                                    }
                                }
                                break;
                            case 2:
                                {
                                    DDIC_Reg_read(str);
                                    for (int j = 0; j < 100000; j++)
                                    {
                                        Application.DoEvents();
                                    }
                                }
                                break;
                            case 3:
                                {
                                    Thread.Sleep(Convert.ToInt16(str));
                                    log_txt.Text += "delay:" + str + "\r\n";
                                    statusFlag = previousFlag;
                                }
                                break;
                            case 4:
                                {

                                }
                                break;
                            default:
                                break;
                        }
                        flow_list.Focus();
                    }
                }
            }

        }
        private void device_delay_ms(string delay)
        {
            byte[] Send_buf = new byte[2 + 5];
            Send_buf[0] = 0x80;//NT38360
            Send_buf[1] = 0x03;//NT38360
            Send_buf[2] = 2;
            int a = Convert.ToInt16(delay);
            Send_buf[3] = (byte)(a >> 8);
            Send_buf[4] = (byte)(a & 0xff);


            CRCData.CalculateCrc16(Send_buf, out Send_buf[2 + 5 - 2], out Send_buf[2 + 5 - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 2 + 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        private void button1_Click_1(object sender, EventArgs e)
        {

            btnPrevPic(1, 4, 1, 233, 67, 20, 25, 255);
        }
        private void btnPrevPic(int shapeType, int RGBWtype, double mult, int position_x, int position_y, int single_size, int round_with, int gray_index)       //双击 载入 BMP图片shapeType 0=rectangle 1=circle RGBWtype 0=R,1=G,2=B,3=W
        {
            Int32 HACT_True = (int)frmHelp.HACT.Value;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = (int)frmHelp.VACT.Value;
            Int32 m_txlen = 0;
            Int32 j = 0;
            FileStream aFile;
            byte tep;
            Bitmap image1 = new Bitmap(HACT_True, VACT_True, PixelFormat.Format24bppRgb);
            if (shapeType == 1)
            {
                for (int i = 0; i < HACT_True; i++)
                {
                    for (int jt = 0; jt < VACT_True; jt++)
                    {
                        if ((((i - position_x) * (i - position_x) + (jt - position_y) * (jt - position_y)) > (single_size * single_size)) && (((i - position_x) * (i - position_x) + (jt - position_y) * (jt - position_y)) < ((single_size + round_with) * (single_size + round_with))))
                        {
                            image1.SetPixel(i, jt, Color.FromArgb(0, 0, 0));
                        }
                        else
                            image1.SetPixel(i, jt, Color.FromArgb(gray_index, gray_index, gray_index));
                    }
                }
            }
            else if (shapeType == 0)
            {
                for (int i = 0; i < HACT_True; i++)
                {
                    for (int jt = 0; jt < VACT_True; jt++)
                    {
                        switch (RGBWtype)
                        {
                            case 0:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(255, 0, 0));
                                }
                                break;
                            case 1:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(0, 255, 0));
                                }
                                break;
                            case 2:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(0, 0, 255));
                                }
                                break;
                            case 3:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(255, 255, 255));
                                }
                                break;
                            case 4:
                                {
                                    if (((Math.Abs(i - position_x) > single_size) && (Math.Abs(jt - position_y) > single_size) &&
                                        (Math.Abs(i - position_x) < (round_with + single_size)) && (Math.Abs(jt - position_y) < (round_with + single_size)))
                                        | (((Math.Abs(i - position_x) <= single_size) && (Math.Abs(jt - position_y)) > single_size) && (Math.Abs(jt - position_y) < (round_with + single_size)))
                                        | (((Math.Abs(jt - position_y) <= single_size) && (Math.Abs(i - position_x)) > single_size) && (Math.Abs(i - position_x) < (round_with + single_size)))
                                        )
                                    {
                                        image1.SetPixel(i, jt, Color.FromArgb(0, 0, 0));
                                    }
                                    else
                                        image1.SetPixel(i, jt, Color.FromArgb(gray_index, gray_index, gray_index));
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            image1.Save("./123456789.bmp", ImageFormat.Bmp);
            //MemoryStream ms = null;
            //string temp = null;
            //{
            //    ms = new MemoryStream();
            //    image1.Save(ms, ImageFormat.Bmp);
            //    byte[] byteImage = new Byte[ms.Length];
            //    byteImage = ms.ToArray();

            //    for (int i = 0; i < 54; i++)
            //    {
            //        temp= temp+"，"+byteImage[i].ToString();
            //    }
            //    System.Diagnostics.Debug.Print(temp);
            //}
            //System.Diagnostics.Debug.Print("=================");

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;

            aFile = new FileStream("./123456789.bmp", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            FileStream bfile;
            //bfile = new FileStream(image1.GetHbitmap(),FileAccess.Read);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);
            Int32 BMoffset = ((TemFileContent[13] << 24) + (TemFileContent[12] << 16) + (TemFileContent[11] << 8) + TemFileContent[10]);
            HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);



            HACT_Skip = HACT_True;

            try
            { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                frmHelp.comPort.Write(TemFileContent, 0, 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
            //-----------------------------------
            try
            {
                //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
                j = 1;
                while (j <= VACT_True)
                {
                    if (HACT_True % 4 != 0)
                        aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + BMoffset, SeekOrigin.Begin);
                    else
                        aFile.Seek((VACT_True - j) * HACT_True * 3 + BMoffset, SeekOrigin.Begin);

                    ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                    try
                    {
                        frmHelp.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        break;
                    }
                    m_txlen += ByteReaded;
                    //  progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                    // label14.Text = progressBar1.Value.ToString() + "%";
                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                    j++;
                }
                TemFileContent[0] = 0x5A;
                try
                {
                    frmHelp.comPort.Write(TemFileContent, 0, 1);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
                aFile.Close();
                // File.Delete("./123456789.bmp");
            }
            catch
            {
                MessageBox.Show("unexpected exception occured!");
            }

        }



        private void button2_Click(object sender, EventArgs e)
        {
            //Gamma_write_all(1);
            //get_send_buf_direct();
            //adjust_direct((int)gamma_set.Value, 333, 444, 777);

            CA410_Measure_Lxy_38360();// CA410_Measure1_Lxy();
        }

        private double CASDK_y;
        private double CASDK_x;

        double Lv2, sx2, sy2;

        public CaSDK CaSDKOb1j = new CaSDK();
        public void CA410_Measure_Lxy_38360()
        {

            CaSDKOb1j.CA410_Measure_Lxy();
            Lv2 = CaSDKOb1j.Lv;
            sx2 = CaSDKOb1j.sx;
            sy2 = CaSDKOb1j.sy;
            lux1.Text = Lv2.ToString("0.00");
            sx1.Text = sx2.ToString("0.00");
            sy1.Text = sy2.ToString("0.00");
        }

    }

}
#endregion
